﻿using System;
using System.IO;
using System.Windows.Forms;

namespace ChromiumUpdater
{
    public partial class FrmRevert : IconForm
    {
        public string SelectedBuild;
        private void frmBuilds_Load(object sender, EventArgs e)
        {
            GetBuilds();
            btnOK.Enabled = false;
            btnDelete.Enabled = false;
        }

        private void GetBuilds()
        {
            listView1.Clear();
            var c = new Common();
            var builds = c.GetBuildDirs();

            listView1.View = View.Details;
            listView1.FullRowSelect = true;
            listView1.Sorting = SortOrder.Ascending;

            // Create columns for the items and subitems.
            listView1.Columns.Add("build", 100, HorizontalAlignment.Left);
            listView1.Columns.Add("date", -2, HorizontalAlignment.Left);

            foreach (var build in builds)
            {
                var item1 = new ListViewItem(build.Name, 0);
                item1.SubItems.Add(build.LastWriteTime.ToString());

                listView1.Items.Add(item1);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            SelectedBuild = listView1.SelectedItems[0].SubItems[0].Text;
            DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            string build = listView1.SelectedItems[0].SubItems[0].Text;
            if (build != null)
            {
                var dr = MessageBox.Show(
                    "Do you sure you want to delete build "+build,
                    "Warning",
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2);

                if (dr == DialogResult.Yes)
                {                    
                    btnOK.Enabled = false;
                    btnDelete.Enabled = false;
                    Directory.Delete(build,true);
                }
            }
            GetBuilds();
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedIndices != null)
            {
                btnDelete.Enabled = true;
                btnOK.Enabled = true;
            }
        }
    }
}
